# server.py
import socket
import threading

# 服务器地址和端口
SERVER_HOST = 'localhost'
SERVER_PORT = 32345
PUB_VARIBLE_UI_STOP = '空'


def handle_client(client_socket):
    global PUB_VARIBLE_UI_STOP
    try:
        while True:
            # 接收客户端的数据
            data = client_socket.recv(1024)
            if not data:
                break
            print(f'收到客户端消息: {data.decode()}')

            # 发送响应给客户端
            message = '' + data.decode()
            returnMessage = ''
            arrYehaibo = message.split('|')
            if arrYehaibo[0] == 'READ':
                if arrYehaibo[1] == 'PUB_VARIBLE_UI_STOP':
                    returnMessage = PUB_VARIBLE_UI_STOP
                    print(f'读取变量:PUB_VARIBLE:' + PUB_VARIBLE_UI_STOP)
            elif arrYehaibo[0] == 'WRITE':
                if arrYehaibo[1] == 'PUB_VARIBLE_UI_STOP':
                    PUB_VARIBLE_UI_STOP = arrYehaibo[2]
                    returnMessage = '写成功'
            else:
                pass
            client_socket.sendall(returnMessage.encode())
    except Exception as e:
        print(f'处理客户端连接时出错: {e}')
    finally:
        # 关闭客户端连接
        client_socket.close()


def start_server():
    # 创建TCP套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        # 绑定服务器地址和端口
        server_socket.bind((SERVER_HOST, SERVER_PORT))

        # 开始监听连接，请求等待队列的最大长度设置为128
        server_socket.listen(128)
        print(f'服务器启动，监听 {SERVER_HOST}:{SERVER_PORT} ...')

        while True:
            # 等待客户端连接
            client_socket, client_address = server_socket.accept()
            print(f'接受来自 {client_address} 的连接')

            # 使用线程处理客户端请求
            client_thread = threading.Thread(target=handle_client, args=(client_socket,))
            client_thread.start()

    except Exception as e:
        print(f'服务器启动失败: {e}')
    finally:
        # 关闭服务器套接字
        server_socket.close()


if __name__ == "__main__":
    start_server()
